package cn.nuaa.cms.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;

import cn.nuaa.cms.model.CollectInfo;
import cn.nuaa.cms.model.Department;
import cn.nuaa.cms.model.Info;
import cn.nuaa.cms.model.LoginInfo;
import cn.nuaa.cms.model.LookInfo;
import cn.nuaa.cms.model.Organize;
import cn.nuaa.cms.model.Relation;
import cn.nuaa.cms.model.User;
import cn.nuaa.cms.util.CosineSimilarAlgorithm;
import cn.nuaa.cms.util.Node;
import cn.nuaa.cms.util.QiniuUtil;
import cn.nuaa.cms.util.RongCloud;
import cn.nuaa.cms.util.TokenReslut;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
import com.qiniu.util.StringUtils;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

public class IndexController extends Controller {
	private static String appKey = PropKit.get("appKey");
	private static String appSecret = PropKit.get("appSecret");
	private static String portraitUri = PropKit.get("portraitUri");

	/**
	 * 用户注册
	 */
	public void reg() {
		String result = "";
		String code = getPara(0);
		String token = CacheKit.get("phoneToken", "code");
		if (token.equals(code)) {
			String jsonStr = HttpKit.readData(getRequest());
			User regUser = JSONObject.parseObject(jsonStr, User.class);
			String account = regUser.getAccount();
			User user = User.dao.findByAccount(regUser.getAccount());
			if (user == null) {
				RongCloud cloud = RongCloud.getInstance(appKey, appSecret);
				try {
					TokenReslut reslut = cloud.user.getToken(account, account,
							portraitUri);
					regUser.setImtoken(reslut.getToken());
				} catch (Exception e) {
					System.out.println("获取融云token异常" + account);
				}
				String randomString = UUID.randomUUID().toString()
						.substring(0, 5);
				regUser.setUsername("NUAA" + randomString);
				regUser.setEmail(randomString + "@nuaa.edu.cn");
				regUser.setPicurl("http://obq1lvsd9.bkt.clouddn.com/thum/1439892157_314989.png");
				regUser.save();
				result = "success";
			} else {
				result = "ERROR1";
			}
		} else {
			result = "ERROR2";
		}
		renderText(result);
	}

	public void getToken() throws ApiException {
		String phone = getPara("phone");
		String token = CacheKit.get("phoneToken", "code");
		if (StringUtils.isNullOrEmpty(token)) {
			token = (int) (Math.random() * 10000) + "";
			CacheKit.put("phoneToken", "code", token);
		}
		String url = "http://gw.api.taobao.com/router/rest";
		String appkey = "23383344";
		String secret = "f78c8593d890c0e6d9dcfaddbeb2530b";
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend("123456");
		req.setSmsType("normal");
		req.setSmsFreeSignName("南航社团");
		req.setSmsParamString("{\"code\":\"" + token + "\"}");
		req.setRecNum(phone);
		req.setSmsTemplateCode("SMS_25605875");
		AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
		renderText("发送成功，请注意查收");
	}

	/**
	 * 用户登录
	 */
	public void login() {
		String jsonStr = HttpKit.readData(getRequest());
		User loginUser = JSONObject.parseObject(jsonStr, User.class);
		User user = User.dao.findByAccountAndPassword(loginUser);
		if (user != null) {
			renderJson(user);
			// 保存登录日志
			LoginInfo loginInfo = new LoginInfo();
			loginInfo.setAccount(user.getAccount());
			loginInfo.setUsername(user.getUsername());
			loginInfo.save();
		} else {
			renderNull();
		}
	}

	/**
	 * 重置密码为nuaa
	 */
	public void resetPassword() {
		String code = getPara("code");
		String account = getPara("account");
		String token = CacheKit.get("phoneToken", "code");
		if (token.equals(code)) {
			User user = User.dao.findByAccount(account);
			user.setPassword("nuaa");
			user.update();
			renderText("重置为nuaa");
		} else {
			renderText("验证码错误");
		}

	}

	public void updUser() {
		User user = getModel(User.class, "", true);
		String account = getPara(0);
		User u = User.dao.findByAccount(account);
		user.setId(u.getId());
		user.update();
		renderText("修改成功");
	}

	/**
	 * 查询好友
	 */
	public void search() {
		String userAccount = getPara(0);
		User user = User.dao.findUsersByAccount(userAccount);
		renderJson(user);
	}

	/**
	 * 删除好友
	 */
	public void delFriend() {
		String username = getPara("username");
		String account = getPara("account");
		User user = User.dao.findByUsername(username);
		Relation.dao.deleteByUsernameAndAccount(account, user.getAccount());
		renderText("删除成功");
	}

	/**
	 * 好友列表
	 */
	public void listFriends() {
		String userAccount = getPara(0);
		List<Relation> relations = Relation.dao.findByUserAccount(userAccount);
		List<Node> parentNodes = new ArrayList<Node>();
		for (Relation relation : relations) {
			Node node = new Node();
			String groupName = relation.getGroupName();
			node.setText(groupName);
			node.setHref("group");
			// 通过groupname userAccount
			List<Relation> relationList = Relation.dao
					.findByGroupNameAndUserAccount(groupName, userAccount);
			List<Node> nodes = new ArrayList<Node>();
			for (Relation relation2 : relationList) {
				String friendAccount = relation2.getFriendAccount();
				User user = User.dao.findByAccount(friendAccount);
				Node userNode = new Node();
				userNode.setText(user.getUsername());
				userNode.setHref("user");
				nodes.add(userNode);
			}
			node.setNodes(nodes);
			parentNodes.add(node);
		}
		renderJson(parentNodes);
	}

	public void upload() {
		UploadFile uploadFile = getFile();
		String type = getPara(0);
		String uploadpath = uploadFile.getUploadPath() + "/"
				+ uploadFile.getOriginalFileName();
		String key = type + "/" + uploadFile.getOriginalFileName();
		try {
			QiniuUtil.upload(uploadpath, key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		uploadFile.getFile().delete();
		renderJson(key);
	}

	/**
	 * 发布信息
	 */
	public void addInfo() {
		String result = "";
		Info info = getModel(Info.class, "", true);
		info.setUser(getPara(0));
		String title = info.getTitle();
		info.setThumpic("http://obq1lvsd9.bkt.clouddn.com/" + info.getThumpic());
		Info tempInfo = Info.dao.findByTitle(title);
		if (tempInfo == null) {
			if (info.getTop() == null) {
				info.setTop(0);
			}
			if (info.getThumpic() == null) {
				info.setThumpic("http://obq1lvsd9.bkt.clouddn.com/thum/mmexport1479899786090.jpg");
			}
			info.save();
			result = "保存成功";
		} else {
			result = "标题已经存在，不要重复提交";
		}
		renderText(result);
	}

	/**
	 * 查询置顶信息
	 */
	public void listTopInfo() {
		List<Info> infos = Info.dao.findInfoByType(1);
		renderJson(infos);
	}

	/**
	 * 查询非置顶信息
	 */
	public void listUnTopInfo() {
		List<Info> infos = Info.dao.findInfoByType(0);
		renderJson(infos);
	}

	/**
	 * 查看信息
	 */
	public void getNewsInfo() {
		Integer id = getParaToInt(0);
		Info info = Info.dao.findById(id);
		renderJson(info);
	}

	/**
	 * 添加好友
	 */
	public void appendFriend() {
		String userAccount = getPara("userAccount");
		String targetAccount = getPara("targetAccount");
		String userGroup = getPara("userGroup");
		Relation temp = Relation.dao.findByUserAndFriend(userAccount,
				targetAccount);
		if (temp == null) {
			Relation relation1 = new Relation();
			relation1.setUserAccount(userAccount);
			relation1.setFriendAccount(targetAccount);
			relation1.setGroupName(userGroup);
			relation1.setStatus(0);// 设置为初始状态
			relation1.save();
			Relation relation2 = new Relation();
			relation2.setUserAccount(targetAccount);
			relation2.setFriendAccount(userAccount);
			relation2.setGroupName(userGroup);
			relation2.setStatus(0);// 设置为初始状态
			relation2.save();
			renderText("添加成功");
		} else {
			renderText("你们已经是好友，请勿重新添加");
		}
	}

	/**
	 * 通讯录
	 */
	// @Before(CacheInterceptor.class)
	// @CacheName("nodes")
	public void listDepartments() {
		List<Organize> organizes = Organize.dao.findAll();
		List<Node> fatherNodes = new ArrayList<Node>();
		for (Organize organize : organizes) {
			Node organizeNode = new Node();
			organizeNode.setText(organize.getName());
			organizeNode.setHref("organize");

			List<Node> parentNodes = new ArrayList<Node>();
			List<Department> departments = Department.dao
					.findByOrganizeId(organize.getId());
			for (Department department : departments) {
				Node node = new Node();
				String departName = department.getName();
				node.setText(departName);
				node.setHref("department");
				parentNodes.add(node);
				Department depart = Department.dao.findByDepartName(departName);
				// 查询部门下的用户
				List<User> userList = User.dao.findByDepartId(depart.getId());
				List<Node> childrenNodes = new ArrayList<Node>();
				for (User user : userList) {
					Node childrenNode = new Node();
					childrenNode.setText(user.getUsername() + "-"
							+ user.getAccount());
					childrenNode.setHref("user");
					childrenNodes.add(childrenNode);
				}
				node.setNodes(childrenNodes);
			}
			organizeNode.setNodes(parentNodes);
			fatherNodes.add(organizeNode);
		}
		renderJson(fatherNodes);
	}

	/**
	 * 通过部门名称获取部门
	 */
	public void getDepartment() {
		String departName = getPara("departName");
		Department department = Department.dao.findByDepartName(departName);
		renderJson(department);
	}

	public void getOrganize() {
		String organizeName = getPara("organizeName");
		Organize organize = Organize.dao.findByOrganizeName(organizeName);
		renderJson(organize);
	}

	public void getUser() {
		String temp = getPara("username");
		String username = temp.split("-")[0];
		String account = temp.split("-")[1];
		User user = User.dao.findByAccount(account);
		renderJson(user);
	}

	/**
	 * 通过账户查询用户
	 */
	public void getUserByAccount() {
		String account = getPara(0);
		User user = User.dao.findByAccount(account);
		renderJson(user);
	}

	/**
	 * 通过用户名查询用户
	 */
	public void getUserByUsername() {
		String username = getPara("username");
		User user = User.dao.findByUsername(username);
		renderJson(user);
	}

	public void lookInfo() {
		String userAccount = getPara("account");
		int infoId = getParaToInt("infoId");
		LookInfo info = LookInfo.dao
				.findByAccountAndInfoid(userAccount, infoId);
		if (info == null) {
			LookInfo lookInfo = new LookInfo();
			lookInfo.setInfoId(infoId);
			lookInfo.setUserAccount(userAccount);
			lookInfo.save();
		} else {
			info.setCreateTime(new Date());
			info.update();
		}
		renderText("true");
	}

	/**
	 * 收藏文章
	 */
	public void collectInfo() {
		String userAccount = getPara("account");
		int infoId = getParaToInt("infoId");
		CollectInfo collectInfo = new CollectInfo();
		CollectInfo temp = CollectInfo.dao.findByInfoIdAndAccount(infoId,
				userAccount);
		if (temp == null) {
			collectInfo.setInfoId(infoId);
			collectInfo.setUserAccount(userAccount);
			collectInfo.save();
			renderText("收藏成功");
		} else {
			renderText("已收藏,请勿重新操作");
		}

	}

	/**
	 * 删除收藏
	 */
	public void delCollect() {
		String userAccount = getPara("account");
		int infoId = getParaToInt("infoId");
		String sql = "DELETE FROM collect_info WHERE user_account = ? and info_id = ?";
		Db.update(sql, userAccount, infoId);
		renderText("删除收藏成功");
	}

	/**
	 * 删除浏览
	 */
	public void delLook() {
		String userAccount = getPara("account");
		int infoId = getParaToInt("infoId");
		String sql = "DELETE FROM look_info WHERE user_account = ? and info_id = ?";
		Db.update(sql, userAccount, infoId);
		renderText("删除浏览成功");
	}

	/**
	 * 获取用户藏的信息
	 */
	public void getInfosByAccount() {
		String account = getPara(0);
		String sql = "SELECT i.*,ci.create_time FROM collect_info ci,info i WHERE ci.info_id = i.id AND ci.user_account = ? ORDER BY ci.create_time DESC";
		List<Record> records = Db.find(sql, account);
		renderJson(records);
	}

	public void getLookInfosByAccount() {
		String account = getPara(0);
		String sql = "SELECT i.*,li.create_time FROM look_info li,info i WHERE li.info_id = i.id AND li.user_account = ? ORDER BY li.create_time DESC";
		List<Record> records = Db.find(sql, account);
		renderJson(records);
	}

}
